package com.ruoyi.common.utils.kiam;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class KiamUtil {
    // 接口服务地址
    static String restSever = "http://1.85.55.225:8888/kiam/urm/service/"; //
    //static String restSever = "http://59.218.241.89:28084/urm/service/"; //
   ;
    // 接口服务地址
    public static String ossRestSever = "http://1.85.55.225/sso";
    // 身份系统提供给应用对接的应用标识
    public static String appKey = "0528918565740544";
    // 身份系统签发给应用对接的密钥
    public static String pwd = "d6e5eaeb74939a3d633bb6c136d3ad8c885da4e5";

    public static void setCommonHeaders(HttpRequestBase http, String getQueryParam) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchProviderException {
        // 随机数
        String once = RandomStringUtils.randomAlphanumeric(32);
        String signMethod = "SHA-256";
        // 时间戳
        Long ts = Calendar.getInstance().getTime().getTime();
        String commonParamUrl = String.format("appKey=%s" + "&" + "ts=%s" + "&" + "once=%s" + "&" + "signMethod=%s", appKey, ts, once, signMethod);

        String getAllParamUrl = commonParamUrl + "&" + getQueryParam;
        // 对参数签名，并放入请求header中的signData参数中

        // 签名数据
        String signData = TokenUtil.getSignature(pwd, getAllParamUrl, signMethod);
        // 添加header参数 appCode、timestamp、 signatureonce、signature
        http.addHeader("appKey", appKey);
        http.addHeader("ts", ts.toString());
        http.addHeader("once", once);
        http.addHeader("signMethod", signMethod);
        http.addHeader("signData", signData);
    }

    public static JSONObject get(String url,String getQueryParam) throws Exception {
        // 创建HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String getFullUrl = restSever + url + "?" + getQueryParam;
        HttpGet httpGet = new HttpGet(getFullUrl);
        setCommonHeaders(httpGet, getQueryParam);
        String urlStr = httpGet.getURI().toString();
        if (StringUtils.endsWith(urlStr, "/")) {
            urlStr = StringUtils.removeEnd(urlStr, "/");
        }

        httpGet.setURI(new URI(urlStr));
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();
        httpGet.setConfig(requestConfig);
        System.out.println("urlStr in request:" + httpGet.getURI().toString());

        // 执行请求
        CloseableHttpResponse response = httpclient.execute(httpGet);
        // 取响应的结果
        int statusCode = response.getStatusLine().getStatusCode();
        // 打印响应结果
        if (statusCode == HttpStatus.SC_OK) {
            String resp = EntityUtils.toString(response.getEntity(), "utf-8");
            return JSONObject.parseObject(resp);
        }
        return null;
    }

    public static List<SysDept> syncDept(Long startTime) throws Exception {
        List<SysDept> all = new ArrayList<>();
        int i = 0;
        while (true) {
            List<SysDept> depts = syncDept(i,startTime);
            all.addAll(depts);
            i++;
            if (depts.size() == 0) {
                break;
            }
        }
        return all;
    }

    public static List<SysDept> syncDept(Integer pageNum,Long startTime) throws Exception {
        startTime = 0L;
        String getQueryParam = "pageNum="+pageNum+"&startTime="+startTime;
        JSONObject response = get("V3/res/orgs", getQueryParam);
        JSONArray data = response.getJSONArray("data");
        if(data == null){
            return new ArrayList<>();
        }
        List<SysDept> depts = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject orgJson = data.getJSONObject(i);
            SysDept dept = new SysDept();
            dept.setOrgId(orgJson.getString("ORG_ID"));
            dept.setOrgParentId(orgJson.getString("PARENT_ID"));
            dept.setOrgType(orgJson.getString("ORG_TYPE"));
            dept.setOrgNo(orgJson.getString("ORG_NO"));
            dept.setDeptName(orgJson.getString("ORG_NAME"));
            dept.setShortDeptName(orgJson.getString("ORG_NAME_SHORT"));
            dept.setStatus(orgJson.getIntValue("ORG_STATUS") >= 2000 ? "0" : "1");
            dept.setShowOrder(orgJson.getString("ORG_SHOW_ORDER"));
            if(dept.getDeptName().contains("建设保障")){
                System.out.println("111111111");
            }
            depts.add(dept);
        }
        return depts;
    }
    public static List<SysUser> syncUser(Long startTime) throws Exception {
        startTime = 0L;
        List<SysUser> all = new ArrayList<>();
        int i = 0;
        while (true) {
            List<SysUser> users = syncUser(i,startTime);
            all.addAll(users);
            i++;
            if (users.size() == 0) {
                break;
            }
        }
        return all;
    }

    public static List<SysUser> syncUser(Integer pageNum,Long startTime) throws Exception {
        String getQueryParam = "pageNum="+pageNum+"&startTime="+startTime;
        JSONObject response = get("V3/res/users", getQueryParam);
        JSONArray data = response.getJSONArray("data");
        if(data == null){
            return new ArrayList<>();
        }
        List<SysUser> users = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject orgJson = data.getJSONObject(i);
            SysUser user = new SysUser();
            user.setKiamUserId(orgJson.getString("USER_ID"));
            user.setKiamOrgId(orgJson.getString("ORG_ID"));
            user.setKiamUserNo(orgJson.getString("USER_ND"));
            user.setKiamJobId(orgJson.getString("USER_JOB_ID"));
            user.setKiamJobTitle(orgJson.getString("JOB_TITLE"));
            user.setKiamJobType(orgJson.getString("JOB_TYPE"));
            user.setNickName(orgJson.getString("USER_NAME"));
            user.setPhonenumber(orgJson.getString("MOBILE"));
            user.setEmail(orgJson.getString("EMAIL"));
            user.setUserName(orgJson.getString("MOBILE"));
            if(StrUtil.isNotBlank(user.getUserName())){
                user.setUserName(orgJson.getString("USER_ID"));
            }
            user.setStatus(orgJson.getIntValue("JOB_STATUS") >= 2000 ? "0" : "1");
            user.setSex(orgJson.getIntValue("SEX") == 1 ? "0" : "1");
            user.setIdNumber(orgJson.getString("IDCARD_NO"));
            user.setOfficePhone(orgJson.getString("OFFICE_PHONE"));
            users.add(user);
        }
        return users;
    }
    public static List<SysUser> syncUser2(Long startTime) throws Exception {
        List<SysUser> all = new ArrayList<>();
        int i = 0;
        while (true) {
            List<SysUser> users = syncUser2(i,startTime);
            all.addAll(users);
            i++;
            if (users.size() == 0) {
                break;
            }
        }
        return all;
    }

    public static List<SysUser> syncUser2(Integer pageNum,Long startTime) throws Exception {
        String getQueryParam = "pageNum="+pageNum+"&cascade=1&ORG_NO=01000000000000000";
        JSONObject response = get("V4/res/users/orgusers", getQueryParam);
        JSONArray data = response.getJSONArray("data");
        if(data == null){
            return new ArrayList<>();
        }
        List<SysUser> users = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject orgJson = data.getJSONObject(i);
            SysUser user = new SysUser();
            user.setKiamUserId(orgJson.getString("USER_ID"));
            user.setKiamOrgId(orgJson.getString("ORG_ID"));
            user.setKiamUserNo(orgJson.getString("USER_ND"));
            user.setKiamJobId(orgJson.getString("USER_JOB_ID"));
            user.setKiamJobTitle(orgJson.getString("JOB_TITLE"));
            user.setKiamJobType(orgJson.getString("JOB_TYPE"));
            user.setNickName(orgJson.getString("USER_NAME"));
            user.setPhonenumber(orgJson.getString("MOBILE"));
            user.setEmail(orgJson.getString("EMAIL"));
            user.setUserName(orgJson.getString("MOBILE"));
            if(StrUtil.isNotBlank(user.getUserName())){
                user.setUserName(orgJson.getString("USER_ID"));
            }
            user.setStatus(orgJson.getIntValue("JOB_STATUS") >= 2000 ? "0" : "1");
            user.setSex(orgJson.getIntValue("SEX") == 1 ? "0" : "1");
            user.setIdNumber(orgJson.getString("IDCARD_NO"));
            user.setOfficePhone(orgJson.getString("OFFICE_PHONE"));
            users.add(user);
        }
        return users;
    }
}
